package com.dxf.sysadmin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxf.common.utils.GlobalConstant;
import com.dxf.common.utils.ResultJson;
import com.dxf.sysadmin.entity.*;
import com.dxf.sysadmin.entity.qo.MyPage;
import com.dxf.sysadmin.entity.vo.CourseClazzTeacherVo;
import com.dxf.sysadmin.entity.vo.EvaluteResultVo;
import com.dxf.sysadmin.entity.vo.ExcelResultVo;
import com.dxf.sysadmin.entity.vo.ResultVo;
import com.dxf.sysadmin.mapper.EvaluteResultMapper;
import com.dxf.sysadmin.service.*;
import com.dxf.sysadmin.utils.EchartsData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * 评价结果 服务实现类
 */
@Service
public class EvaluteResultServiceImpl extends ServiceImpl<EvaluteResultMapper, EvaluteResult> implements EvaluteResultService {

    @Autowired
    EmpService empService;
    @Autowired
    DeptService deptService;
    @Autowired
    EvaluteTypeService evaluteTypeService;
    @Autowired
    CourseClazzTeacherService courseClazzTeacherService;
    @Autowired
    StudentService studentService;

    /**
     *评价结果列表分页查询
     */
    @Override
    public ResultJson resultPage(MyPage qry) {
        Page<EvaluteResultVo> page = new Page<>(qry.getPage(), qry.getLimit());

        Map<String, Object> map = new HashMap<>();
        Page<EvaluteResultVo> courseVoPage = baseMapper.selectEvaluteResultPage(page);

        map.put("rows",courseVoPage.getRecords());
        map.put("total",courseVoPage.getTotal());
        return ResultJson.ok().data(map);
    }

    /**
     *系主任评价结果数据查询
     */
    @Override
    public ResultJson departmentResult(Long uid, Long tid) {
        //所有系员工
        List<Emp> empList=new ArrayList<>();
        List<EvaluteType> list = evaluteTypeService.list();
        double sum = list.stream().mapToDouble(EvaluteType::getWeight).sum();
        //对应教师
        Emp one = empService.getOne(new QueryWrapper<Emp>().
                lambda().eq(Emp::getUserId, uid));
        //系部门
        List<Dept> deptList = deptService.list(new QueryWrapper<Dept>().
                lambda().eq(Dept::getParentId, one.getDeptId()));
        deptList.forEach(y->{
            //部门员工
            empList.addAll(empService.list(new QueryWrapper<Emp>().
                    lambda().eq(Emp::getDeptId, y.getId()).ne(Emp::getDuty,1)));
        });
        return ResultJson.ok().data("emps",empList.stream().map(Emp::getName).
                collect(Collectors.toList())).data("types",list.stream().
                map(EvaluteType::getName).collect(Collectors.toList())).
                data("echartsData",getEchartsData(empList,tid,list));
    }

    /**
     *室主任评价结果数据查询
     */
    @Override
    public ResultJson directorResult(Long uid, Long tid) {
        List<EvaluteType> list = evaluteTypeService.list();
        //对应教师
        Emp one = empService.getOne(new QueryWrapper<Emp>().
                lambda().eq(Emp::getUserId, uid));
        //同部门教师 .ne(Emp::getId,one.getId()))
        List<Emp> empList = empService.list(new QueryWrapper<Emp>().
                lambda().eq(Emp::getDeptId, one.getDeptId()).ne(Emp::getId,one.getId()));

        return ResultJson.ok().data("emps",empList.stream().map(Emp::getName).
                collect(Collectors.toList())).data("types",list.stream().
                map(EvaluteType::getName).collect(Collectors.toList())).
                data("echartsData",getEchartsData(empList,tid,list));
    }

    /**
     *评教汇总excel数据
     */
    @Override
    public ResultJson getExcelResult(Long tid) {
        DecimalFormat df=new DecimalFormat("0.00");
        //教师
        List<Emp> emps = empService.list(new QueryWrapper<Emp>().lambda().eq(Emp::getDuty, 2));
        //部门
        List<Dept> depts = deptService.list();
        //课表
        List<CourseClazzTeacher> cct = courseClazzTeacherService.list();
        //学生
        List<Student> students = studentService.list();
        List<ExcelResultVo> excel=new ArrayList<>();
        for (Emp emp : emps) {
            ExcelResultVo excelVo = new ExcelResultVo();
            //评教记录
            List<ResultVo> resultVos = baseMapper.selectResultVo(tid, emp.getId());
            excelVo.setName(emp.getName());
            //获取部门
            List<Dept> collect = depts.stream().filter(n -> n.getId().equals(emp.getDeptId())).collect(Collectors.toList());
            excelVo.setDepartment(collect.get(0).getName());
            //学生评价
            //课表
            List<CourseClazzTeacher> course = cct.stream().filter(m -> m.getTeacherId().equals(emp.getId())).collect(Collectors.toList());
            int sum=0;
            for (CourseClazzTeacher courseClazzTeacher : course) {
                List<Student> clazzStu = students.stream()
                        .filter(p -> p.getClazzId()
                                .equals(courseClazzTeacher.getClazzId())).collect(Collectors.toList());
                sum +=clazzStu.size();
            }
            //学生应评
            excelVo.setStuShouldNum(sum);
            List<ResultVo> stuResult = resultVos.stream().filter(o -> o.getTypeId().equals(GlobalConstant.STUDENT_TYPE_ID)).collect(Collectors.toList());
            //学生实评
            if (stuResult.size()!=0){
                excelVo.setStuRealNum(stuResult.get(0).getNum());
                //学生总分
                excelVo.setStuScore(Double.parseDouble(df.format(stuResult.get(0).getAvgScore()*0.3)));
            }else{
                excelVo.setStuRealNum(0);
                //学生总分
                excelVo.setStuScore((double) 0);
            }


            List<ResultVo> self = resultVos.stream().filter(o -> o.getTypeId().equals(GlobalConstant.TEACHER_ZERO_SELF_TYPE_ID)).collect(Collectors.toList());
            if (self.size()!=0){
                excelVo.setTeaSelfRealNum(1);
                //教师自评总分
                excelVo.setTeaSelfScore(Double.parseDouble(df.format(self.get(0).getAvgScore()*0.15)));
            }else{
                excelVo.setTeaSelfRealNum(0);
                //教师自评总分
                excelVo.setTeaSelfScore((double) 0);
            }

            //教师互评
            List<ResultVo> mutual = resultVos.stream().filter(o -> o.getTypeId().equals(GlobalConstant.TEACHER_ZERO_MUTUAL_TYPE_ID)).collect(Collectors.toList());
            //同部门教师
            List<Emp> empEq = emps.stream().filter(q -> q.getDeptId().equals(emp.getDeptId())).collect(Collectors.toList());
            int empEqNum=empEq.size()-1;
            if (empEqNum<0){
                empEqNum=0;
            }
            excelVo.setTeaMutualShouldNum(empEqNum);
            if (mutual.size()!=0){
                excelVo.setTeaMutualRealNum(mutual.get(0).getNum());
                //教师互评总分
                excelVo.setTeaMutualScore(Double.parseDouble(df.format(mutual.get(0).getAvgScore()*0.25)));
            }else{
                excelVo.setTeaMutualRealNum(0);
                //教师互评总分
                excelVo.setTeaMutualScore((double) 0);
            }


            List<ResultVo> director = resultVos.stream().filter(o -> o.getTypeId().equals(GlobalConstant.TEACHER_ONE_TYPE_ID)).collect(Collectors.toList());
            if (director.size()!=0){
                excelVo.setDirectorRealNum(1);
                //教师自评总分
                excelVo.setDirScore(Double.parseDouble(df.format(director.get(0).getAvgScore()*0.2)));
            }else{
                excelVo.setDirectorRealNum(0);
                //教师自评总分
                excelVo.setDirScore((double) 0);
            }

            //系评价
            List<ResultVo> department = resultVos.stream().filter(o -> o.getTypeId().equals(GlobalConstant.TEACHER_TWO_TYPE_ID)).collect(Collectors.toList());
            if (department.size()!=0){
                excelVo.setDepartmentRealNum(1);
                excelVo.setDepScore(Double.parseDouble(df.format(department.get(0).getAvgScore()*0.45)));
            }else{
                excelVo.setDepartmentRealNum(0);
                excelVo.setDepScore((double) 0);
            }
            excel.add(excelVo);
        }

        return ResultJson.ok().data("rows",excel).data("total",excel.size());
    }

    /**
     *获取Echarts数据
     */
    private List<EchartsData> getEchartsData( List<Emp> empList, Long tid,List<EvaluteType> list){
        double sum = list.stream().mapToDouble(EvaluteType::getWeight).sum();
        List<EchartsData> echartsData=new ArrayList<>();
        //遍历类型
        list.forEach(x->{
            EchartsData data= new EchartsData();
            List<Double> doubles=new ArrayList<>();
            data.setType(x.getName());
            //每个教师该评教类型分数
            empList.forEach(y->{
                List<EvaluteResult> list1 = list(new QueryWrapper<EvaluteResult>().lambda().
                        eq(EvaluteResult::getTaskId, tid).eq(EvaluteResult::getTypeId, x.getId()).
                        eq(EvaluteResult::getTeacherId,y.getId()));
                //平均值
                OptionalDouble average = list1.stream().mapToDouble(EvaluteResult::getScore).average();
                //如果存在值，则返回 true ，否则返回 false 。
                if(average.isPresent()){
                    DecimalFormat df=new DecimalFormat("0.00");
                    double d=average.getAsDouble()*(x.getWeight()/sum);
                    doubles.add(Double.parseDouble(df.format(d)));
                }else {
                    doubles.add((double) 0);
                }
            });
            data.setSource(doubles);
            echartsData.add(data);
        });
        return echartsData;
    }
}
